package com.framework.core.event.aop;

import com.alibaba.fastjson.JSON;
import com.framework.common.auto.ThreadLocalUtils;
import com.framework.common.utils.IpAndAddrUtil;
import com.framework.common.utils.SnowflakeIdWorker;
import com.framework.core.entity.SysLog;
import com.framework.core.event.anno.WebLogIgnore;
import com.framework.core.service.SysLogService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * 统一日志处理切面
 */
@Aspect
@Component
@Log4j2
public class WebLogAspect {

    @Lazy
    @Autowired
    private SysLogService sysLogService;

    //配置所有控制器请求
//    @Pointcut("execution(public * com.sunjee.fx.portal.models.*.controller.*.*(..))")
    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void webLog() {
    }
//    //定义切点 @Pointcut
//    //在注解的位置切入代码
//    @Pointcut("@annotation(com.sunjee.web.common.annotation.MyLog)")
//    public void logPoinCut() {
//    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        SysLog sysLog = loadSysLog(joinPoint, startTime, request, methodSignature);
        if (sysLog != null) {
            sysLogService.saveSysLog(sysLog);
        }
        return result;
    }

    public SysLog loadSysLog(ProceedingJoinPoint joinPoint, long startTime, HttpServletRequest request, MethodSignature methodSignature) {
        try {
            SysLog webLog = new SysLog();
            webLog.setId(SnowflakeIdWorker.nextId());
            Method method = methodSignature.getMethod();
            if (method.isAnnotationPresent(WebLogIgnore.class)) {
                return null;
            }
            if (method.isAnnotationPresent(ApiOperation.class)) {
                ApiOperation log = method.getAnnotation(ApiOperation.class);
                webLog.setOperation(log.value());
            }
            long endTime = System.currentTimeMillis();
            webLog.setMethod(request.getMethod());
            webLog.setUri(request.getRequestURI());
            webLog.setUrl(request.getRequestURL().toString());
            Object parameter = getParameter(method, joinPoint.getArgs());
            if (parameter != null) {
                try {
                    webLog.setParams(JSON.toJSONString(parameter));
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
            }
            String userAgent = request.getHeader("user-agent").toLowerCase();
            webLog.setUserAgent(userAgent);
            webLog.setOsName(IpAndAddrUtil.getOsName(request));
            webLog.setIp(IpAndAddrUtil.getIpAddr(request));
            webLog.setLogType("操作日志");
//        webLog.setResult(JSON.toJSONString(result));
            long timeMillis = (endTime - startTime) / 1000;
            webLog.setSpendTime((int) timeMillis);
            webLog.setUserid(ThreadLocalUtils.getUserId() == null ? "" : ThreadLocalUtils.getUserId().toString());
            webLog.setName(ThreadLocalUtils.getUserInfo() == null ? "" : ThreadLocalUtils.getUserInfo().getName());
            webLog.setCorpId(ThreadLocalUtils.getCorpId());
            webLog.setCreateId(ThreadLocalUtils.getUserId());
            webLog.setCreateDate(new Date());
            return webLog;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return null;
        }
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }


}
